package stealth.novaposhta;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

public class NetUtil {
 
    String remoteUrl;
    
    public static String Encoding = "windows-1251"; 
 
    public NetUtil(String downloadUrl) {
        remoteUrl = downloadUrl;
    }
 
    public String toString(String rString) {
        URL urlString;
        InputStream iStream = null;
        try {
            urlString = new URL(remoteUrl);
            URLConnection uCon = urlString.openConnection();
            iStream = uCon.getInputStream();
            if (iStream != null) {
                Writer writer = new StringWriter();
 
                char[] buffer = new char[1024];
                Reader reader = new BufferedReader(new InputStreamReader(
                        iStream, Encoding));
 
                int n;
                while ((n = reader.read(buffer)) != -1) {
                    writer.write(buffer, 0, n);
                }
 
                iStream.close();
                rString = writer.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rString;
    }
 
    public void toFile(File fName) {
        try {
            URL urlString = new URL(remoteUrl);
 
            HttpURLConnection urlConnection = (HttpURLConnection) urlString
                    .openConnection();
 
            urlConnection.setRequestMethod("GET");
            urlConnection.setDoOutput(true);
 
            urlConnection.connect();
 
            FileOutputStream fileOutput = new FileOutputStream(fName);
 
            InputStream inputStream = urlConnection.getInputStream();
 
            byte[] buffer = new byte[1024];
            int bufferLength = 0;
 
            while ((bufferLength = inputStream.read(buffer)) > 0) {
                fileOutput.write(buffer, 0, bufferLength);
 
            }
            fileOutput.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}